package com.youdoneed.friends.friends;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.friends.model.RemoveRecommendFriends;
import com.youdoneed.friends.query.QRemoveRecommendFriends;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RemoveRecommendFriendsService {

    private final Logger logger = LoggerFactory.getLogger(RemoveRecommendFriendsService.class);

    @Autowired
    private SQLQueryFactory queryFactory;
    private QRemoveRecommendFriends qRemoveRecommendFriends = QRemoveRecommendFriends.RemoveRecommendFriends;

    public List<String> findRemoveFriendIds(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        SQLQuery<String> query = queryFactory.select(qRemoveRecommendFriends.friendId)
                .from(qRemoveRecommendFriends)
                .where(qRemoveRecommendFriends.userId.eq(userId));
        return query.fetch();
    }

    public long saveRemoveRecommendFriends(RemoveRecommendFriends record) {
        if (StringUtils.hasText(record.getRemoveRecommendId())) {
            return queryFactory.update(qRemoveRecommendFriends)
                    .populate(record)
                    .where(qRemoveRecommendFriends.removeRecommendId
                            .eq(record.getRemoveRecommendId()))
                    .execute();
        } else {
            record.setRemoveRecommendId(GlobalIdWorker.nextString());
            record.setCreateTime(new Date());
            return queryFactory.insert(qRemoveRecommendFriends)
                    .populate(record)
                    .execute();
        }
    }

}
